import {
    login,
    logout,
    userinfo
} from "@/api";
import {
    setToken,
    getToken,
    removeToken
} from "@/utils/token";
import {
    Message
} from 'element-ui'
const state = {
    token: getToken(),
    roles: [],
};
const getters = {
    roles: state => state.roles,
    token: state => state.token,
};
const mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_ROLES(state, roles) {
        state.roles = roles
    }

};
const actions = {
    loginActions({
        commit
    }, from) {
        return new Promise((resolve, reject) => {
            login(from).then((res) => {
                let {
                    code,
                    data: {
                        token
                    },
                } = res.data;
                if (code == 20000) {
                    commit('SET_TOKEN', token)
                    setToken(token); //保存token
                    resolve(code)
                } else {
                    Message.error("用户名或密码错误");
                }
            }).catch(err => {
                reject(err)
            });
        })
    },
    getInfo({
        commit
    }) {
        return new Promise((resolve, reject) => {
            userinfo().then(res => {
                let {
                    code,
                    data: {
                        roles
                    },
                    data
                } = res.data;
                if (code == 20000) {
                    commit('SET_ROLES', roles)
                    resolve(data)
                }
            })
        }).catch(err => {
            reject(err)
        });
    },
    logoutActions({
        commit
    }) {
        return new Promise((resolve, reject) => {
            logout().then((res) => {
                let {
                    code,
                    data
                } = res.data;
                if (code == 603) {
                    resolve(code)
                    commit('SET_ROLES', [])
                    commit('SET_TOKEN', '')
                    removeToken();
                    Message.success(data);
                } else {
                    Message.error(data);
                }
            }).catch(err => {
                reject(err)
            });
        })
    }
};
export default {
    state,
    getters,
    mutations,
    actions,
};